package com.loser.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.loser.redis.core.RedisHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Callable;

/**
 * 缓存工具类
 *
 * @author alan
 * @date 2022/5/17 16:20
 */

public class RedisCache {

    private static final Logger log = LoggerFactory.getLogger(RedisCache.class);
    private static final String EMPTY = "{}";
    private final RedisHandler redisHandler;

    public RedisCache(RedisHandler redisHandler) {
        this.redisHandler = redisHandler;
    }

    public <T> T loadCache(String cacheKey, Class<T> tClass, Callable<T> loader) {
        return loadCache(cacheKey, tClass, loader, null);
    }

    public <T> T loadCache(String cacheKey, Class<T> tClass, Callable<T> loader, Long expired) {

        String value = redisHandler.get(cacheKey);
        if (StringUtils.isEmpty(value)) {
            try {
                T result = loader.call();
                if (expired == null) {
                    expired = DateUtils.SECONDS_PER_HOUR;
                }
                if (result != null) {
                    redisHandler.set(cacheKey, JSON.toJSONString(result), expired);
                } else {
                    redisHandler.set(cacheKey, EMPTY, DateUtils.SECONDS_PER_MINUTE);
                }

                return result;
            } catch (Exception exception) {
                log.error("load cache error,cacheKey={}", cacheKey, exception);
            }
        }

        if (Objects.equals(EMPTY, value)) {
            return null;
        }
        return JSON.parseObject(value, tClass);

    }

    public <T> List<T> loadCaches(String cacheKey, Class<T> tClass, Callable<List<T>> loader) {
        return loadCaches(cacheKey, tClass, loader, null);
    }

    public <T> List<T> loadCaches(String cacheKey, Class<T> tClass, Callable<List<T>> loader, Long expired) {

        String value = redisHandler.get(cacheKey);
        if (StringUtils.isEmpty(value)) {
            try {
                List<T> result = loader.call();
                if (expired == null) {
                    expired = DateUtils.SECONDS_PER_HOUR;
                }
                if (CollectionUtil.isNotEmpty(result)) {
                    redisHandler.set(cacheKey, JSON.toJSONString(result), expired);
                } else {
                    redisHandler.set(cacheKey, JSON.toJSONString(new ArrayList<>()), DateUtils.SECONDS_PER_MINUTE);
                }
                return result;
            } catch (Exception exception) {
                log.error("load cache error,cacheKey={}", cacheKey, exception);
            }
        }
        return JSON.parseArray(value, tClass);

    }

    public void clearCache(String cacheKey) {
        redisHandler.del(cacheKey);
    }

}
